import re

from rest_framework import serializers
from login import models

def check_phonenumber(value):
    ret = re.match(r"^1[3-9]\d{9}$", value)
    if ret:
        data = models.User.objects.filter(phonenumber=value)
        if data:
            raise serializers.ValidationError(detail={"msg": "数据库中已存在数据"})
        return value
    raise serializers.ValidationError(detail={"msg": "手机号不符合规范"})

class PhonenumberSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = "__all__"
        extra_kwargs = {
            "phonenumber": {
                "validators": [check_phonenumber]
            }
        }
